import { Module } from "vuex";
import type { vuexStore, bwPermission } from '@/store/type/interface';
import { RouteRecordRaw } from 'vue-router';
import asyncRoutes from "@/router/asyncRouter";


// 判断当前用户的权限
const hasPermission = (roles: any, route: any) => {
  // 对于根页面进行默认展示
  if(route.path == '/home') return true
  // 对于父节点下的跟路由默认添加
  if(route.path == '') return true
  // 对于详情路由进行默认添加
  if(route.path.split('/:').length == 2){
    if(roles.find((item:any)=> item.url == route.path.split(':')[0])){
      return true
    }else{
      return false
    }
  }
  // 对于路由后面携带参数？开头的结尾理由进行code码筛选
  // 对于路由为#的进行code筛选
  if(roles.some((role:any) => route.meta.code == role.code)) {
    return true
  }else{
    return false
  }
}

// 筛选出符合当前用户的权限
export const filterAsyncRoutes = (routes: RouteRecordRaw[], roles: any[]) => {
  const res: RouteRecordRaw[] = []
  routes.forEach(route => {
    const r = { ...route }
    if (hasPermission(roles, r)) {
      if (r.children) {
        r.children = filterAsyncRoutes(r.children, roles)
      }
      res.push(r)
    }
  })
  return res
}

const state: bwPermission = {
  routes: [],
  dynamicRoutes: []
}

const mutations = {
  GenerateRoutes(state:bwPermission, roles: RouteRecordRaw[]){
    if(!roles || roles.length == 0){ return }
    let accessedRoutes;
    // 拿到后端生成路由表，获取其中的url地址
    const url = roles;
    const urllist:any = []
    url.forEach((v:any)=>{
      urllist.push({ url:v.url,code:v.code })
    })
    accessedRoutes = filterAsyncRoutes(asyncRoutes,urllist)

    // 页面不存在的情况下会跳到404页面
    accessedRoutes.push(
      {
        path: '*', 
        redirect: '/404',
        meta:{
          name: 'notFound',
        }
      },
    )
    
    state.dynamicRoutes = accessedRoutes
  }
}

const actions = {

}

// 定义user数据模型
export const permissionModel:Module<bwPermission, vuexStore> = {
  state: state,
  mutations: mutations,
  actions: actions
}

// 导出模型方法
type name = keyof typeof mutations
type disPatchName = keyof typeof actions

export const permissionModelUse = ( store:any )=>{
  return {
    commit: (name:name, data?: any)=>{
      store.commit(name, data)
    },
    dispatch:(name: disPatchName, data?:any)=>{
      store.dispatch(name, data)
    },
    state: store.state.permissionModel as bwPermission
  }
}

